<template>
    <div class="common_page" :style="{background: this.detail.style.backColor}"
    >
        <div class="main_content" ref="mainContent" :style="{
        width: detail.style.position.w + 'px',
        height: detail.style.position.h + 'px',
        background: this.detail.style.backColor,
      }">
            <el-card style="margin-bottom:5px;">
                <div class="card_top">
                    <div class="card_title">设备能源搜索</div>
                    <div class="card_btn">
                        <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['energy:equimentEnergy:query']" :loading="buttonLoading" @click="search">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" v-hasPermi="['energy:equimentEnergy:query']" :loading="buttonLoading" @click="resetFields">重置</el-button>
                    </div>
                </div>
                <el-form :model="searchData" ref="queryForm" :inline="true" label-width="68px" style="margin-bottom:-20px;">
                    <el-row>

                        <el-col :span="6">
                            <el-form-item label="选择时间" prop="date">
                                <!-- :picker-options="pickerOptions" -->
                                <el-date-picker
                                    v-if="searchData.dateType == 3"
                                    v-model="searchData.date"
                                    type="monthrange"
                                    style="width:225px"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    @change="dateChange"
                                >
                                </el-date-picker>
                                <el-date-picker
                                    v-else
                                    v-model="searchData.date"
                                    type="daterange"
                                    style="width:225px"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    @change="dateChange"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" style="margin-left: 30px">
                            <el-form-item label="日期维度" prop="dateType">
                                <el-select v-model="searchData.dateType" @change="dateTypeChange" style="width: 200px" clearable  placeholder="请选择">
                                    <el-option
                                        v-for="item in dimensionList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>



                    <!-- <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['energy:equimentEnergy:query']" :loading="buttonLoading" @click="search">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" v-hasPermi="['energy:equimentEnergy:query']" :loading="buttonLoading" @click="resetFields">重置</el-button>
                    </el-form-item> -->
                </el-form>
            </el-card>
            <div class="page_content" style="width: 100%">
                <div class="page_content_head" v-loading="chartsLoading">
                    <div class="left_echat">
                        <div ref="bar_chart_equipment" style="width: 100%;height: 246px;" />
                    </div>
                    <!--                    <div class="right_echat">
                                            <div ref="pie_chart_equipment" style="width: 100%;height: 246px;" />
                                        </div>-->
                </div>
                <div class="page_content_bottom">
                    <sysTable
                        :data="setTableData"
                        :columns="setTableColumns"
                        :curr-page="searchData.pageNum"
                        :total-page="pageTotal"
                        :page-size="searchData.pageSize"
                        @sizeChange="sizeChange"
                        @currentChange="currentChange"
                        @header-click="headerClick"
                    >

                        <template #unitEnergy_header>
                            <div class="header_with_unit">
                                <div style="line-height: 20px">单位能耗</div>
                                <div style="line-height: 20px">(能耗单位/小时)</div>
                            </div>
                        </template>
                    </sysTable>
                </div>
            </div>
        </div>
    </div>
</template>

<script>

import BaseView from './View';
import {mapGetters} from "vuex";
import {equipentEnergyCharts, equipentEnergyList} from "@/views/energy/api/energy/energyMonitoring";
import * as echarts from "echarts";
import {energyClassification} from "@/views/energy/api/energy/workShopEnergy";
import {
    getbuildingList,
    getEquipentList,
    getFloorList,
    getWorkShopList
} from "@/views/energy/api/energy/equipmentEnergy";
import sysTable from "@/views/energy/components/SysTable/index.vue";
export default {
    name: 'view-warn',
    components: {sysTable},
    extends: BaseView,
    computed:{
        headerChange(){
            return this.detail.style.header;
        },
        ...mapGetters(["theme"]),
        cssVars() {
            return {
                "--color": this.theme
            };
        }
    },
    watch:{
        headerChange(newVal,oldVal){
            // console.log("绑定数据变化了",newVal);
            if(oldVal){

            }
        }
    },
    data() {
        return {
            searchData: {
                buildingId: '',
                workshopIds: null,
                floor: null,
                guid: null,
                deviceIds: null,
                classifyId: '',
                deviceName: '',
                date: [new Date(),new Date()],
                // type: 1,
                dateType: 1,
                pageSize: 10,
                pageNum: 1
            },
            setTableData: [],
            pageTotal: 0,
            buildList: [],
            floorList: [],
            workShopList: [],
            dimensionList: [
                {
                    id: 1,
                    name: '时'
                },
                {
                    id: 2,
                    name: '日'
                },
                {
                    id: 3,
                    name: '月'
                },
            ],
            deviceList: [],
            classifyList: [],
            setTableColumns: [
                {
                    label: '设备名称',
                    prop: 'deviceName',
                    minWidth: '180',
                    align: 'center',
                    fixed: 'left',
                    showOverflowTooltip: true
                },
                {
                    label: '总费用',
                    prop: 'equipmentConPrice',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '电量(kW·h)',
                    prop: 'powerConsumption',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '水量(m³)',
                    prop: 'waterConsumption',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '气量(m³)',
                    prop: 'gasConsumption',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '热量(GJ)',
                    prop: 'hotType',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '尖电(kW·h)',
                    prop: 'spikesType',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '峰电(kW·h)',
                    prop: 'peaksType',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '平电(kW·h)',
                    prop: 'parityType',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '谷电(kW·h)',
                    prop: 'lowebbType',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                // {
                //   label: '有功电量(kW·h)',
                //   prop: 'activePower',
                //   width: '180',
                //   align: 'center',
                //   showOverflowTooltip: true
                // },
                // {
                //   label: '无功电量(Kvar)',
                //   prop: 'reactivePower',
                //   width: '180',
                //   align: 'center',
                //   showOverflowTooltip: true
                // },
                {
                    label: '冷冻水(mj)',
                    prop: 'coolingType',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '软化水(m³)',
                    prop: 'softeningType',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '自来水(m³)',
                    prop: 'tapType',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '仪表压空(m³)',
                    prop: 'lnstrumentAirPressure',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '洁净压空(m³)',
                    prop: 'cleanCompressedAir',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '空调热能(m³)',
                    prop: 'airHotEnergy',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: 'cop',
                    prop: 'equipmentCon',
                    width: '180',
                    align: 'center',
                    showOverflowTooltip: true
                },
                // {
                //   label: '单位能耗',
                //   prop: 'unitEnergy',
                //   width: '180',
                //   align: 'center',
                //   showOverflowTooltip: true
                // },
                {
                    label: '时间',
                    prop: 'createdDate',
                    width: '180',
                    align: 'center',
                    fixed: 'right',
                    showOverflowTooltip: true
                },
            ],
            pieEquipentL: [],
            pieEquipentY: [],
            barEquipentX: [],
            barEquipentY: [],
            chartsLoading: false,
            choiceDate0: '',
            dateComponentType: 'daterange', // daterange年月日， monthrange月
            pickerOptions: {
                // 设置不能选择的日期
                onPick: ({ maxDate, minDate }) => {
                    this.choiceDate0 = minDate.getTime();
                    if (maxDate) {
                        this.choiceDate0 = '';
                    }
                },
                disabledDate:
                    (time) => {
                        let choiceDateTime = new Date(this.choiceDate0).getTime();
                        const minTime = new Date(choiceDateTime).setMonth(new Date(choiceDateTime).getMonth() - 1) +  24 * 60 * 60 * 1000;
                        const maxTime = new Date(choiceDateTime).setMonth(new Date(choiceDateTime).getMonth() + 1) -  24 * 60 * 60 * 1000;
                        const min = minTime;
                        const newDate = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1;
                        const max = newDate <= maxTime ? newDate : maxTime;
//如果已经选中一个日期 则 返回 该日期前后一个月时间可选
                        if (this.choiceDate0) {
                            return time.getTime() < min || time.getTime() > max;
                        }
//若一个日期也没选中 则 返回 当前日期以前日期可选
                        return time.getTime() > newDate;
                    }
            },
            buttonLoading: false,
            isExpansion: false,



            classStyle:null,
            config:{

            },
            header: [],
            timer:null,
            key:0,
            realData:[],
            loading:false,
        }
    },

    mounted() {
        // this.initBarEquipment()
        // this.initPieEquipment()
        this.getbuildingList()
        this.getenergyClassification()
        this.getPageList()
        this.getPageCharts()
        this.detail.style.data=[];

    },
    methods: {
        search() {
            if(this.searchData.date && this.searchData.date.length > 0) {
                const isPass = this.jumpDates()
                if(!isPass) {
                    return false
                }
            }
            this.buttonLoading = true
            this.searchData.pageNum = 1
            this.getPageList(),
                this.getPageCharts()

        },
        resetFields() {
            this.workShopList = []
            this.floorList = []
            this.deviceList = []
            this.searchData = {
                buildingId: '',
                workshopIds: null,
                deviceIds: null,
                classifyId: '',
                deviceName: '',
                //type: 1,
                date: [],
                dateType: 1,
                pageSize: 10,
                pageNum: 1
            }
            this.search()
        },
        sizeChange(val) {
            this.searchData.pageSize = val
            this.getPageList()
        },
        currentChange(val) {
            this.searchData.pageNum = val
            this.getPageList()
        },
        /** 收起展开操作按钮操作 */
        changeExpansion() {
            this.isExpansion = !this.isExpansion
        },
        getPageList() {
            const objs = {
                buildingId: this.searchData.buildingId,
                workshopIds: this.searchData.workshopIds,
                floor: this.searchData.floor,
                deviceIds: this.searchData.deviceIds,
                classifyId: this.searchData.classifyId,
                deviceName: this.searchData.deviceName,
                begin: this.searchData.date? this.searchData.date[0]: '',
                end: this.searchData.date? this.searchData.date[1]: '',
                timeType: this.searchData.type,
                dateType: this.searchData.dateType,
                pageSize: this.searchData.pageSize,
                pageNum: this.searchData.pageNum,
                guid: this.$route.query.guid
            }
            // const objss = {
            //   equipmentEnergyParam: objs
            // }
            console.log(this.$route.query.guid,'@@')
            this.searchData.guid = this.$route.query.guid
            equipentEnergyList(objs).then(res=> {
                console.log(res,'@@@')
                this.setTableData = res.data.list
                this.pageTotal = res.data.total || 0

            })
        },

        getPageCharts() {

            this.chartsLoading = true
            const objs = {
                buildingId: this.searchData.buildingId,
                floor: this.searchData.floor,
                workshopIds: this.searchData.workshopIds,
                deviceIds: this.searchData.deviceIds,
                classifyId: this.searchData.classifyId,
                deviceName: this.searchData.deviceName,
                begin: this.searchData.date? this.searchData.date[0]: '',
                end: this.searchData.date? this.searchData.date[1]: '',
                timeType: this.searchData.type,
                dateType: this.searchData.dateType,
                pageSize: this.searchData.pageSize,
                pageNum: this.searchData.pageNum,
                type: this.searchData.type,
                energyType: this.searchData.energyType,
                guid: this.$route.query.guid
            }
            equipentEnergyCharts(objs).then(res=> {
                console.log(res.data, '图表数据')
                if(JSON.stringify(res.data) === "{}") {
                    this.barEquipentX = []
                    this.pieEquipentL = []
                    this.pieEquipentY = []
                    this.barEquipentY = [
                        {
                            name: '总费用',
                            type: 'line',
                            data: [],
                            showSymbol: false,
                            smooth: true,
                            areaStyle: {
                                opacity: 0.2,
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    {
                                        offset: 1,
                                        color: 'rgba(51, 153, 255, 0.20)'
                                    },
                                    {
                                        offset: 0,
                                        color: 'rgba(51, 153, 255, 1)'
                                    }
                                ])
                            }
                        }
                    ]
                    this.initBarEquipment()
                    //this.initPieEquipment()
                    this.chartsLoading = false
                    this.buttonLoading = false
                    return
                }
                console.log(res, '图表数据3333')
                const chartsData = res.data
                this.barEquipentX = Object.keys(chartsData.brokenLine).sort()
                this.pieEquipentL = Object.keys(chartsData.pieGraph).sort()
                this.barEquipentY = []
                this.pieEquipentY = []
                const arr = []
                this.pieEquipentL.map(item=> {
                    let totalNum = chartsData.pieGraph[item] || 0
                    const obj = {
                        name: item,
                        value: totalNum
                    }
                    this.pieEquipentY.push(obj)
                })
                this.barEquipentX.map(item=> {
                    let totalNum = this.searchData.energyType ? (chartsData.brokenLine[item][this.searchData.energyType] || 0) : chartsData.brokenLine[item].equipmentConPrice
                    arr.push(totalNum)
                })
                this.barEquipentY = [
                    {
                        name: '总费用',
                        type: 'line',
                        data: arr,
                        showSymbol: false,
                        smooth: true,
                        areaStyle: {
                            opacity: 0.2,
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 1,
                                    color: 'rgba(51, 153, 255, 0.20)'
                                },
                                {
                                    offset: 0,
                                    color: 'rgba(51, 153, 255, 1)'
                                }
                            ])
                        }
                    }
                ]
                this.initBarEquipment()
                //this.initPieEquipment()
                this.chartsLoading = false
                this.buttonLoading = false
            })
        },
        getenergyClassification() {
            energyClassification().then(res => {
                this.classifyList = res.data
            })
        },
        getEquipmentEchart() {

        },
        initBarEquipment() {
            const myEcharts = echarts.init(this.$refs.bar_chart_equipment);
            myEcharts.setOption({
                color: ['#3399FF'],
                backgroundColor: '#fff',
                tooltip: {
                    trigger: 'item',
                    formatter: ' {b} : {a} : {c}'
                },
                grid: {
                    left: '0%',
                    right: '2%',
                    bottom: '2%',
                    top: '4%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: this.barEquipentX,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#606266',
                                fontSize: '12px'
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        splitLine: {
                            show: false
                        },
                        axisLabel: {
                            formatter: "{value}",
                            textStyle: {
                                color: '#606266',
                                fontSize: '12px'
                            }
                        }
                    }
                ],
                series: this.barEquipentY
            }, true)
        },
        getbuildingList() {
            getbuildingList().then(res=> {
                this.buildList = res.data || []
            })
        },
        getFloorList(val) {
            const obj = {
                buildId: val
            }
            getFloorList(obj).then(res=> {
                console.log(res, '楼层列表')
                this.floorList = res.data || []
            })
        },
        getWorkShopList(val) {
            const obj = {
                buildingId: val
            }
            getWorkShopList(obj).then(res=> {
                console.log(res.data, '3333')
                this.workShopList = res.data || []
            })
        },
        getEquipentList(val) {
            getEquipentList(val).then(res=> {
                this.deviceList = res.data
                console.log(res, '设备数据')
            })
        },
        buildChange(val) {
            this.workShopList = []
            this.deviceList = []
            this.floorList = []
            this.searchData.floor = null
            this.searchData.workshopIds = []
            this.searchData.deviceIds = []
            if (val) {
                this.getFloorList(val)
            }
        },
        floorChange(val) {
            console.log(val, '变化数据')
            this.workShopList = []
            this.deviceList = []
            this.searchData.workshopIds = []
            this.searchData.deviceIds = []
            if (val) {
                this.getWorkShopList(val)
            }
        },
        workShopChange(val) {
            console.log(val, '3333')
            this.deviceList = []
            this.searchData.deviceIds = []
            const arr = []
            val.map(item=> {
                const obj = {
                    id: item
                }
                arr.push(obj)
            })
            if (val) {
                this.getEquipentList(arr)
            }
        },
        headerClick(val) {
            if(val.property != 'deviceName' && val.property != 'createdDate') {
                this.searchData.energyType = val.property
                this.getPageCharts()
            }
        },
        handleExport() {
            this.buttonLoading = true
            var datas = {
                buildingId: this.searchData.buildingId,
                workshopIds: this.searchData.workshopIds,
                deviceIds: this.searchData.deviceIds,
                classifyId: this.searchData.classifyId,
                deviceName: this.searchData.deviceName,
                begin: this.searchData.date? this.searchData.date[0]: '',
                end: this.searchData.date? this.searchData.date[1]: '',
                timeType: this.searchData.type,
                pageSize: '',
                pageNum: ''
            }
            const obj = JSON.parse(JSON.stringify(datas))
            // exportEquipent(obj).then(res=> {
            //   const fileName = '设备能源监控记录.xlsx'
            //   saveExcel(res.data, fileName)
            // })
            this.download('energy/monitoring/equipmentByReport', {
                ...obj
            }, '设备能源监控记录.xlsx')
            this.buttonLoading = false
        },
        dateChange() {
            if(this.searchData.date && this.searchData.date.length > 0) {
                if(this.searchData.date[0] == this.searchData.date[1]) {
                    this.searchData.type = 2
                } else {
                    this.searchData.type = 1
                }
                this.jumpDates()
            } else {
                this.searchData.type = 1
            }
        },
        dateTypeChange() {
            this.searchData.date = []
        },
        jumpDates() {
            if(this.searchData.date[0] == this.searchData.date[1] ) {
                if(this.searchData.dateType != 1) {
                    this.$message({
                        message: '选择时间和时间维度规则不匹配',
                        type: 'warning'
                    });
                    this.searchData.date = []
                    return false
                }
            } else {
                if(this.searchData.dateType == 1) {
                    this.$message({
                        message: '选择时间和时间维度规则不匹配',
                        type: 'warning'
                    });
                    this.searchData.date = []
                    console.log(this.searchData.date, '数据332211')
                    return false
                }
            }
            return true
        },



        //格式化时间
        leaveTime(value)
        {
            return value;
            // return moment(value).format('HH:mm');
        },
        /*getList(){
            let query={
                ztGuid:this.$route.query.guid,
                //headListStr:this.headerChange.join(";"),
            }
            //this.loading=true;
          let url="/zutai/bDeviceHistory/getRealDataList"
            request({
            url:url,
            method:"get",
            params: query,

            }).then((res)=>{
                // console.log("实时数据",res.data);
                let sdata=[];
                res.data.forEach(element => {
                    let mdata=[element.reportTime,element.paramName,element.paramValue]
                    sdata.push(mdata)
                });
                this.realData=sdata;
                this.key=new Date().getTime();
                //this.loading=false;
            })
        },*/
    },
    beforeDestroy() {
        clearInterval(this.timer)
        this.timer=null;
    },
}
</script>

<style lang="scss" scoped>

@import '~@/assets/styles/element-variables.scss';

.common_page {
    background-color: #FFFFFF;
    height: 100%;
    width: 100%;
}
.main_content {
    padding: 6px;
}
.page_content {
    padding: 0 20px;
    .page_content_head {
        display: flex;
        padding: 16px;
        .right_echat {
            height: 246px;
            width: 460px;
            padding-left: 20px;
            border-left: 1px solid rgba(0,0,0,0.08);
        }
        .left_echat {
            flex: 1;
        }
    }
}
::v-deep.sys_table {
    .tableHeaderRow {
        cursor: pointer;
        .tableHeaderCell:active {
            opacity: 0.6;
        }
        .tableHeaderCell:last-of-type:active {
            opacity: 1;
        }
        .tableHeaderCell:first-of-type:active {
            opacity: 1;
        }
        .tableHeaderCell:last-of-type{
            cursor: default;
        }
        .tableHeaderCell:first-of-type {
            cursor: default;
        }
    }
}

::v-deep.el-radio-group {
    .el-radio-button {
        .el-radio-button__inner {
            padding: 10px 12px;
            color: #666666;
            font-size: 14px;
        }
    }
    .is-active {
        .el-radio-button__inner {
            background: #fff;
            color: $--color-primary;
        }
    }
}
::v-deep.el-form {
    .el-form-item {
        .el-form-item__content {
            line-height: 32px;
        }
    }
}
</style>
